import Vue from 'vue'
import xurl from './xurl'
import browser from '../../static/js/browser'
import store from '../store/index'
import XCookie from './XCookie'
import XPay from './XPay'

//QQ互联appId
let QQAuthAppId = "101753278";
//支付宝appId
let AlipayAppId_dev = "2019080666132254";
let AlipayAppId_prod = "2019080666135224";

export default {
    /**
     * 去登录
     */
    toLogin() {
        /*如果已经有用户信息了就不用去登录了，仅仅只针对测试板微信授权配置失败做处理   需要调试工具里面关闭第三方登录*/
        let user = store.getters.currentUserFn;
        let third = store.getters.currentThirdFn;
        // if (!!user && user != 'null' && window.location.href.includes('test.haokanhaowan') && XCookie.isOpenThirdAuth()) {
        //     store.dispatch('updateCurrentUser', user);
        //     return true
        // }
        /*未登录需要去微信授权*/
        if (XCookie.isOpenThirdAuth()) {
            if (browser.is_auth_browser()) { //判断是否需要授权的浏览器
                if (!store.state.isThirdLogin) {
                    if (browser.is_weixin()) {
                        this.toLoginByWechat();
                        return false;
                    } else if (browser.is_qq()) {
                        this.toLoginByQQ();
                        return false;
                    } else if (browser.is_alipay()) {
                        this.toLoginByAlipay();
                        return false;
                    }
                }
            }
        }
        return true;
    },
    /**
     * 去登录 by 微信
     */
    toLoginByWechat() {
        let redirectUri = window.encodeURIComponent(Vue.prototype.basePath() + "/wechat_auth");
        // let redirectUri = window.encodeURIComponent("http://test.haokanhaowan.cn/wechat_auth");
        let state = "third_login";
        let url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Vue.prototype.wxPubAppId()
            + "&redirect_uri=" + redirectUri
            + "&response_type=code&scope=snsapi_userinfo&state=" + state
            + "#wechat_redirect";
        window.location.href = url;
    },
    toWxOpen(){
        let redirectUri = window.encodeURIComponent(window.location.href);
        // let redirectUri = window.encodeURIComponent("http://test.haokanhaowan.cn/wechat_auth");
        let state = "third_login";
        let url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Vue.prototype.wxPubAppId()
            + "&redirect_uri=" + redirectUri
            + "&response_type=code&scope=snsapi_userinfo&state=" + state
            + "#wechat_redirect";
        window.location.href = url;
    },
    /**
     * 去登录 by QQ
     */
    toLoginByQQ() {
        let redirectUri = window.encodeURIComponent(Vue.prototype.basePath() + "/qq_auth");
        let state = "third_login"
        let url = "https://graph.qq.com/oauth2.0/authorize?client_id=" + QQAuthAppId
            + "&redirect_uri=" + redirectUri
            + "&response_type=code&scope=get_user_info&state=" + state
            + "&display=mobile";
        window.location.href = url;
    },
    /**
     * 去登录 by alipay
     */
    toLoginByAlipay() {
        let redirectUri = window.encodeURIComponent(Vue.prototype.basePath() + "/alipay_auth");
        let state = "third_login"
        let alipayAppId = (Vue.prototype.isOnline ? AlipayAppId_prod : AlipayAppId_dev);
        let url = "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=" + alipayAppId
            + "&scope=auth_user&redirect_uri=" + redirectUri + "&state=" + state;
        window.location.href = url;
    },
    auth4Wechat(params, callback) {
        XCookie.doAlert('wechat------auth :' + JSON.stringify(params))
        if (params.state == 'third_login') {//第三方登录
            let url = Vue.prototype.NW_API_API_LOCALE_VERSION + '/third/wechat/login'
            let loginParams = {
                terminalType: 'CustomerH5',
                code: params.code,
                deviceType: "好看好玩H5",
                deviceId: Vue.prototype.getDeviceId()
            };
            xurl.postDataJsonLoading(url, loginParams)
                .then(data => {
                    if (data.success) {
                        let nextPage = window.localStorage.getItem(Vue.prototype.NEXTPAGE);
                        XCookie.doAlert('wechat login data :' + JSON.stringify(data));
                        let userId = data.result.userId;
                        let loginThirdId = data.result.thirdId;
                        if (userId) {
                            //保存用户信息,之后跳转页面
                            store.dispatch('updateCurrentUser', data.result).then(()=>{
                                if (callback) {
                                    callback();
                                }
                            })
                        }
                        if (loginThirdId && loginThirdId != 0) {
                            //保存第三方用户信息
                            store.commit('updateCurrentThird', data.result);
                            if (callback) {
                                callback();
                            }
                        }
                        /*!userId && !loginThirdId && */
                        if (!userId && !loginThirdId && data.result.redirect) {
                            window.location.href = data.result.redirect;
                        }
                        if (callback) {
                            callback();
                        }
                    } else {
                        // Vue.$root.$emit("toast", {msg: "登录失败，请重新登录"});
                        console.log("wechat login error:", data.errMsg)
                    }
                })
        }
    },
    prepay4Wechat(params, callback) {
        let url = Vue.prototype.NW_API_API_LOCALE_VERSION + '/h5/wechat/prepay'
        xurl.getSync(url, params).then(data => {
            if (data.success) {
                XPay.toPay(data.result);
            }else{
                XCookie.doAlert('data:'+JSON.stringify(data))
            }
        })
    },
    auth4QQ(params) {
        XCookie.doAlert('qq------auth :' + JSON.stringify(params))
        if (params.state == 'third_login') {//第三方登录
            let url = Vue.prototype.NW_API_API_LOCALE_VERSION + '/third/qq/login'
            let loginParams = {
                terminalType: 'CustomerH5',
                code: params.code,
                deviceType: "好看好玩H5",
                deviceId: Vue.prototype.getDeviceId()
            };
            xurl.postDataJson(url, loginParams)
                .then(data => {
                    XCookie.doAlert("qq login data:" + JSON.stringify(data))
                    console.log("qq login data:", JSON.stringify(data))
                    if (data.success) {
                        store.commit('updateCurrentUser', data.result);
                        if (callback) {
                            callback();
                        }
                    } else {
                        // Vue.$root.$emit("toast", {msg: "登录失败，请重新登录"});
                        console.log("qq login error:", data.errMsg)
                    }
                })
        }
    },
    auth4Alipay(params) {
        XCookie.doAlert('alipay------auth :' + JSON.stringify(params))
        if (params.state == 'third_login') {//第三方登录
            let url = Vue.prototype.NW_API_API_LOCALE_VERSION + '/third/alipay/login'
            let loginParams = {
                terminalType: 'CustomerH5',
                code: params.auth_code,
                deviceType: "好看好玩H5",
                deviceId: Vue.prototype.getDeviceId()
            };
            xurl.postDataJson(url, loginParams)
                .then(data => {
                    XCookie.doAlert("alipay login data:" + JSON.stringify(data))
                    console.log("alipay login data:", JSON.stringify(data))
                    if (data.success) {
                        store.commit('updateCurrentUser', data.result);
                        if (callback) {
                            callback();
                        }
                    } else {
                        // Vue.$root.$emit("toast", {msg: "登录失败，请重新登录"});
                        console.log("alipay login error:", data.errMsg)
                    }
                })
        }
    }
}
